const { dbName, http } = require("../modal/db.config");
const SECRET = dbName;
const { getCurrentDateTime } = require("../modal/time.config");
const STATE = {
  LOW: 0,
  UP: 1,
};
exports.create = async (req, res) => {
  const body = req.body;
  const { content } = body;
  const user = await req.services.UserService.decodeToken();
  const data = {
    content,
    userId: user?.userId,
    reply: "",
    createTime: getCurrentDateTime(),
    updateTime: getCurrentDateTime(),
  };
  const result = await req.services.MessageBoardService.create(data);
  if (result.affectedRows === 1) {
    res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};
//用户修改留言板内容
exports.update = async (req, res) => {
  const body = req.body;
  const { content, id } = body;
  const updateTime = getCurrentDateTime();
  const data = {
    content,
    updateTime,
  };
  const newData = await req.services.MessageBoardService.update(data, { id });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.reply = async (req, res) => {
  const body = req.body;
  const { reply, id } = body;
  const updateTime = getCurrentDateTime();
  const data = {
    reply,
    updateTime,
  };
  const newData = await req.services.MessageBoardService.update(data, { id });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.getDetail = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.MessageBoardService.findById(id);
  if (newData) {
    res.status(200).json({ data: newData, msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};
exports.list = async (req, res) => {
  const body = req.body;
  const { content, page = null, pageSize = null } = body;
  let newData = await req.services.MessageBoardService.getList({
    pageSize: pageSize,
    page: page,
    like: { content },
  });
  let count = await req.services.MessageBoardService.getCount({
    like: { content },
  });

  res.status(200).json({
    data: {
      list: newData,
      total: count,
    },
    msg: "success",
    code: 200,
  });
};

exports.del = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.MessageBoardService.delete(Number(id));
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "删除成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};
